//
//  YZMLoginViewController.m
//  YZMicroStock
//
//  Created by Lv.Dongdong on 16/3/24.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMLoginViewController.h"
#import "YZMHintInputView.h"
#import "NSString+MD5.h"
#import "YZMWebViewController.h"
#import "YZMStockRealModel.h"
#import "YZMTradeTypeDef.h"

@interface YZMLoginViewController () <UITextFieldDelegate>

@property (nonatomic, strong) YZMHintInputView *accountView;
@property (nonatomic, strong) YZMHintInputView *passwordView;
@property (nonatomic, copy) NSString *nextPageName;
@property (nonatomic, strong) NSDictionary *nextPageParams;
@property (nonatomic, copy) NSString *srcPageName;
@property (nonatomic, assign) BOOL dismissFlag;
@property (nonatomic, strong) void (^srcAction)();
@property (nonatomic, strong) void (^backAction)();
@property (nonatomic, assign) BOOL detailUpdatedFlag;
@property (nonatomic, strong) MBProgressHUD *updateHUD;

@end

@implementation YZMLoginViewController {
    UIButton *_loginButton;
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)init {
    if (self = [super init]) {
        self.title = @"登录";
        self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
        self.hidesBottomBarWhenPushed = YES;
        //self.navigationItem.leftBarButtonItem = [YZMAppStyle leftBarItemWithImage:@"icon_white_back" target:self action:@selector(leftBarItemPressed)];
        self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithTitle:@"注册" target:self action:@selector(rightBarItemPressed)];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDetailUpdateNotification) name:YZMUserDetailUpdateNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDetailUpdateNotification) name:YZMUserDetailUpdateFailureNotification object:nil];
        
    }
    return self;
}

- (void)userDetailUpdateNotification{
    
    self.detailUpdatedFlag = YES;
    if (self.updateHUD) {
        
        [self.updateHUD hide:YES];
        [self loginSuccessAcction];
        [MBProgressHUD showMessage: @"登录成功"];
    }
}

- (void) rightBarItemPressed {
    [self resignAllFirstResponder];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    if (self.nextPageName) {
        params[YZNEXTPAGE] = self.nextPageName;
    }
    
    if (self.srcPageName) {
        params[YZSOURCEPAGE] = self.srcPageName;
    }
    
    if (self.nextPageParams) {
        params[YZNEXTPAGEPARAMS] = self.nextPageParams;
    }
    
    if (self.srcAction) {
        params[YZSOURCEACTION]=self.srcAction;
    }
    
    if (self.backAction) {
        params[YZBACKACTION]=self.backAction;
    }
    
    params[YZDismissFlag] = @(self.dismissFlag);
    
    [YZMHCMInstance pushViewControllerWithName:@"register" andParams:params];
}


+ (instancetype)createWithParams: (NSDictionary *)params
{
    
    YZMLoginViewController *ctrl = [[self alloc] init];
    ctrl.nextPageName = params[YZNEXTPAGE];
    ctrl.nextPageParams = params[YZNEXTPAGEPARAMS];
    ctrl.srcPageName  = params[YZSOURCEPAGE];
    ctrl.dismissFlag = [params[YZDismissFlag] boolValue];
    ctrl.srcAction = params[YZSOURCEACTION];
    ctrl.backAction = params[YZBACKACTION];
    return ctrl;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createObjects];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
     [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)createObjects {
    WS(ws)
    self.accountView = [[YZMHintInputView alloc] init];
    [self.view addSubview:self.accountView];
    [self.accountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(ws.view).with.offset(14);
        make.left.equalTo(ws.view);
        make.right.equalTo(ws.view);
        make.height.mas_equalTo(InputViewHeight);
    }];
    
    self.accountView.inputLabel.text = @"账号";
    self.accountView.textField.placeholder = @"请输入昵称或手机号";
    
    self.accountView.lineTopView.hidden=NO;
    
    self.accountView.textField.keyboardType = UIKeyboardTypeDefault;
    self.accountView.textField.delegate = self;
    [self.accountView.textField addTarget:self action:@selector(textValueChanged:) forControlEvents:UIControlEventEditingChanged];
    if (!YZMUserServiceInstance.isValidate && YZMUserServiceInstance.historyUsername) {
        self.accountView.textField.text = YZMUserServiceInstance.historyUsername;
    }
    
    self.passwordView = [[YZMHintInputView alloc] init];
    [self.view addSubview:self.passwordView];
    [self.passwordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(ws.accountView.mas_bottom);
        make.left.right.height.equalTo(ws.accountView);
    }];
    
    self.passwordView.inputLabel.text = @"密码";
    self.passwordView.textField.placeholder = @"请输入密码";
    self.passwordView.textField.secureTextEntry = YES;
    self.passwordView.textField.keyboardType = UIKeyboardTypeDefault;
    self.passwordView.textField.delegate = self;
    [self.passwordView.textField addTarget:self action:@selector(textValueChanged:) forControlEvents:UIControlEventEditingChanged];
    
    self.passwordView.lineBottomView.hidden=NO;
    
    UIButton *getPasswordButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [getPasswordButton setTitle:@"忘记密码" forState:UIControlStateNormal];
    [getPasswordButton setTitleColor:[YZMAppStyle colorForIconColor] forState:UIControlStateNormal];
    [getPasswordButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [getPasswordButton addTarget:self action:@selector(resetPassword) forControlEvents:UIControlEventTouchUpInside];
    [self.passwordView addSubview:getPasswordButton];
    [self.passwordView appendRightWidget:getPasswordButton isShowSegmentLine:YES];
    
    [self.passwordView updateLineIndentationMethod:self.passwordView.lineTopView enumeration:LINE_INDENT_SCENE_LEFT indentValue:ControlSpacing15];
    
    _loginButton = [YZMAppStyle NewsubmitButton];
    [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
    _loginButton.enabled = NO;
    [_loginButton addTarget:self action:@selector(loginBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginButton];
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.view).with.offset(ControlSpacing20);
        make.right.equalTo(ws.view).with.offset(-ControlSpacing20);
        make.top.equalTo(self.passwordView.mas_bottom).with.offset(ControlSpacing30);
    }];
    
}

- (void)loginBtnPressed {
    [self resignAllFirstResponder];
    
    MBProgressHUD *hud = [MBProgressHUD showProgressMessageManual: @"登录中.."];
//    NSLog(@"md5salt:%@", [[@"SSH-YZTZ-COM`" stringByAppendingString:@"zhzhli1818"] lowerMD5]);//md5 加盐登录
    WS(ws)
    [YZMUserServiceInstance loginWithUsername: self.accountView.textField.text password: self.passwordView.textField.text success:^(YZMLoginResultModel *result){
        
        if (result.authenticated) {
            
            if (self.detailUpdatedFlag) {
                [hud hide: NO];
                [ws loginSuccessAcction];
                [MBProgressHUD showMessage: @"登录成功"];
                
            }else{
                
                self.updateHUD = hud;
            }
        }
        else
        {
            [result showMessage];
        }
    } failure:^(NSError *error) {
        [hud hide: YES];
        [error yz_showMessage];
    }];
}

- (void)loginSuccessAcction
{
    YZMWebViewController *vc = [YZMHCMInstance instanceWithControllerName:@"webView"];
    if (vc && [[vc webView].request.URL.absoluteString containsString:@"app/index.html#/simulateStock"]) {
        //刷新H5页面
        [[vc webView] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[[vc webView].request.URL.absoluteString stringByAppendingFormat:@"&v=%d",rand()]]]];
    }
    
    if (self.dismissFlag) {
        
        [YZMCMInstance dismissViewController];
        return;
    }
    
    if (self.nextPageName) {
        if (self.srcPageName) {
            [YZMCMInstance pushAfterName: self.srcPageName withControllerName: self.nextPageName andParams: nil];
        }
        else
        {
            if ([self.nextPageName isEqualToString:@"accountDetail"]) {
                [YZMCMInstance popViewController];
                return;
            }
            if ([self.nextPageParams.allKeys containsObject:@"tradeType"]) {
                NSInteger tradeType = [self.nextPageParams[@"tradeType"] integerValue];
                if (tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
                    [YZMCMInstance popViewController];
                    return;
                }
            }
            [YZMCMInstance pushBeforeName: @"login" withControllerName: self.nextPageName andParams: self.nextPageParams];
        }
    }
    else if (self.srcPageName)
    {
        [YZMCMInstance popViewControllerToControllerName: self.srcPageName animated: YES];
        if (self.srcAction) {
            
            self.srcAction();
        }
    }
    else
    {
        [YZMCMInstance popToRootViewController];
    }
}

- (BOOL)shouldAutoBackToPreviousController{
    
    if (self.backAction) {
        
        self.backAction();
    }
    
    if (self.dismissFlag) {
        
        [YZMCMInstance dismissViewController];
        return NO;
    }
    
    return YES;
}

- (void)resetPassword {
    [self resignAllFirstResponder];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    if (self.nextPageName) {
        params[YZNEXTPAGE] = self.nextPageName;
    }
    
    if (self.srcPageName) {
        params[YZSOURCEPAGE] = self.srcPageName;
    }
    
    if (self.nextPageParams) {
        params[YZNEXTPAGEPARAMS] = self.nextPageParams;
    }
    
    if (self.dismissFlag) {
        params[YZDismissFlag] = @(self.dismissFlag);
    }
    
    [YZMHCMInstance pushViewControllerWithName:@"resetPwd" andParams:params];
}

#pragma mark -- UITextFieldDelegate

- (void)textValueChanged: (UITextField *)field
{
    if (self.accountView.textField.text.length > 0 && self.passwordView.textField.text.length >0) {
        _loginButton.layer.borderWidth=0.0;
        _loginButton.enabled = YES;
    }
    else
    {
        _loginButton.layer.borderWidth=1.0;
        _loginButton.enabled = NO;
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)resignAllFirstResponder {
    [self.passwordView.textField resignFirstResponder];
    [self.accountView.textField resignFirstResponder];
}

@end
